import express, { Application } from 'express';
import bodyParser from 'body-parser';
import { fileOperation, readFile, writeFile } from './utils';
import { ITodoData } from '../src/typings.ts';

const app: Application = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-methods', 'POST,GET,PUT,DELETE,OPTIONS');

  next();
});

app.get('/todolist', function (req, res) {
  const todoList: string = fileOperation('todo.json') as string;

  //响应字符串数据
  res.send(todoList);
});

app.post('/remove', function (req, res) {
  const id: number = parseInt(req.body.id);

  fileOperation('todo.json', (todoList: ITodoData[]) => {
    //删除某一项
    return todoList.filter((todo: ITodoData) => todo.id !== id);
  });

  //响应内容
  res.send({
    msg: 'ok',
    statusCode: '200'
  });
});

app.post('/toggle', function (req, res) {
  const id: number = parseInt(req.body.id);

  fileOperation('todo.json', (todoList: ITodoData[]) => {
    //删除某一项
    return todoList.map((todo: ITodoData) => {
      if (todo.id !== id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
  });

  //响应内容
  res.send({
    msg: 'ok',
    statusCode: '200'
  });
});

app.post('/add', function (req, res) {
  const todo: ITodoData = JSON.parse(req.body.todo);

  fileOperation('todo.json', function (todoList: ITodoData[]) {
    const isExist = todoList.find((t: ITodoData) => t.content === todo.content);

    if (isExist) {
      res.send({
        msg: 'exist',
        statusCode: '100'
      });

      return;
    }

    todoList.push(todo);

    return todoList;
  });

  //响应字符串数据
  res.send({
    msg: 'ok',
    statusCode: '200'
  });
});

app.listen(8080, function () {
  console.log('welcome to Express');
  console.log('Listening on port 8080');
});
